package com.jzo2o.health.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.expcetions.DBException;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.health.mapper.ReservationSettingMapper;
import com.jzo2o.health.model.domain.ReservationSettingMp;
import com.jzo2o.health.model.dto.request.ReservationSettingUpsertReqDTO;
import com.jzo2o.health.model.dto.response.ReservationSettingResDTO;
import com.jzo2o.health.service.ReservationSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.reactive.TransactionalOperator;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Iterator;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 22096
* @description 针对表【reservation_setting(预约设置)】的数据库操作Service实现
* @createDate 2024-12-14 09:46:10
*/
@Service
public class ReservationSettingServiceImpl extends ServiceImpl<ReservationSettingMapper, ReservationSettingMp>
    implements ReservationSettingService{


    /**
     * 按月查询预约设置
     * @param date
     * @return
     */
    @Override
    public List<ReservationSettingResDTO> getReservationSettingByMonth(String date) {
        List<ReservationSettingMp> list = this.lambdaQuery().like(ReservationSettingMp::getOrderDate, date).list();
        if (CollUtils.isEmpty(list)){
            throw new CommonException("不存在数据");
        }
        List<ReservationSettingResDTO> collect = list.stream().map(res -> {
            ReservationSettingResDTO bean = BeanUtils.toBean(res, ReservationSettingResDTO.class);
            LocalDate orderDate = res.getOrderDate();
            bean.setDate(orderDate.toString());
            return bean;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 编辑预约设置
     * @param reservationSettingUpsertReqDTO
     */
    @Override
    public void editNumberByDate(ReservationSettingUpsertReqDTO reservationSettingUpsertReqDTO) {
        Integer count = this.lambdaQuery().eq(ReservationSettingMp::getOrderDate, reservationSettingUpsertReqDTO.getOrderDate()).count();
        if (count<1){
            throw new CommonException("不存在数据");
        }
        boolean update = this.lambdaUpdate().eq(ReservationSettingMp::getOrderDate, reservationSettingUpsertReqDTO.getOrderDate()).set(ReservationSettingMp::getNumber, reservationSettingUpsertReqDTO.getNumber()).update();
        if (!update){
            throw new CommonException("操作失败");
        }
    }

    @Autowired
    private ReservationSettingService reservationSettingService;
    /**
     * 上传文件批量预约设置
     * @param file
     */
    @Override
    public void upload(MultipartFile file) {
        if (file.isEmpty()) {
            throw new CommonException("文件解析失败");
        }

        try {
            // 调用解析Excel的方法
            reservationSettingService.parseExcel(file.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void parseExcel(InputStream inputStream) throws IOException, ParseException {
        try (Workbook workbook = new XSSFWorkbook(inputStream)) {
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
            List<ReservationSettingMp> reservationSettingList=new ArrayList<>();
            Iterator<Row> rowIterator = sheet.iterator();
            boolean isFirstRow = true; // 标志是否为第一行
            while (rowIterator.hasNext()) {
                ReservationSettingMp reservationSettingMp = new ReservationSettingMp();
                Row row = rowIterator.next();
                // 如果是第一行，则跳过
                if (isFirstRow) {
                    isFirstRow = false;
                    continue;
                }
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    switch (cell.getCellType()) {
                        case STRING:
                            String dateString = cell.getStringCellValue();
                            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                            LocalDate localDate = LocalDate.parse(dateString, formatter);
                            reservationSettingMp.setOrderDate(localDate);
                            break;
                        case NUMERIC:
                            reservationSettingMp.setNumber((int) cell.getNumericCellValue());
                            break;
                    }
                }
                reservationSettingList.add(reservationSettingMp);
            }
            if (CollUtils.isEmpty(reservationSettingList)){
                throw new CommonException("集合为空");
            }
            for (ReservationSettingMp settingMp : reservationSettingList) {
                LambdaQueryWrapper<ReservationSettingMp> eq = Wrappers.<ReservationSettingMp>lambdaQuery().eq(ReservationSettingMp::getOrderDate, settingMp.getOrderDate());
                ReservationSettingMp entity = this.getOne(eq);
                if (ObjectUtil.isNotEmpty(entity)){
                    boolean update = this.lambdaUpdate().set(ReservationSettingMp::getNumber, settingMp.getNumber()).eq(ReservationSettingMp::getOrderDate, settingMp.getOrderDate()).update();
                    if (!update){
                        throw new DBException("操作失败");
                    }
                }else {
                    boolean save = this.save(settingMp);
                    if (!save){
                        throw new DBException("操作失败");
                    }
                }
            }
        }
    }
}




